package cn.anecansaitin.not_enough_harness.common.harness_data;

import cn.anecansaitin.not_enough_harness.common.item.ModComponents;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;

public record HarnessCapabilityCD(int cd, int duration) {
    public static final Codec<HarnessCapabilityCD> CODEC = RecordCodecBuilder.create(
            instance ->
                    instance.group(
                                    Codec.INT.fieldOf("cd").forGetter(HarnessCapabilityCD::cd),
                                    Codec.INT.fieldOf("duration").forGetter(HarnessCapabilityCD::duration)
                            )
                            .apply(instance, HarnessCapabilityCD::new)
    );
    public static final StreamCodec<FriendlyByteBuf, HarnessCapabilityCD> STREAM_CODEC = StreamCodec.composite(
            ByteBufCodecs.VAR_INT, HarnessCapabilityCD::cd,
            ByteBufCodecs.VAR_INT, HarnessCapabilityCD::duration,
            HarnessCapabilityCD::new
    );

    public static HarnessCapabilityCD get(ItemStack item) {
        HarnessCapabilityCD harnessCapabilityCD = item.get(ModComponents.HARNESS_CAPABILITY_CD);

        if (harnessCapabilityCD == null) {
            harnessCapabilityCD = new HarnessCapabilityCD(0, 0);
            item.set(ModComponents.HARNESS_CAPABILITY_CD, new HarnessCapabilityCD(0, 0));
        }

        return harnessCapabilityCD;
    }

    public static void set(ItemStack item, int cd, int duration) {
        item.set(ModComponents.HARNESS_CAPABILITY_CD, new HarnessCapabilityCD(cd, duration));
    }
}
